package vn.egame.elockscreen.homelocker;

import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
import vn.egame.elockscreen.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;

/**
 * Created by shaobin on 2014/3/22.
 */
public class HomeKeyLocker {

	private OverlayDialog mOverlayDialog;

	public void lock(Activity activity) {
		if (mOverlayDialog == null) {
			mOverlayDialog = new OverlayDialog(activity);
			mOverlayDialog.show();
		}

		InputMethodManager imm = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

	}

	public void unlock() {
		if (mOverlayDialog != null) {
			mOverlayDialog.dismiss();
			mOverlayDialog = null;
		}
	}

	public OverlayDialog getmOverlayDialog() {
		return mOverlayDialog;
	}

	public void setmOverlayDialog(OverlayDialog mOverlayDialog) {
		this.mOverlayDialog = mOverlayDialog;
	}

	private static class OverlayDialog extends AlertDialog {

		public OverlayDialog(Activity activity) {
			super(activity, R.style.OverlayDialog);
			WindowManager.LayoutParams params = getWindow().getAttributes();
			params.type = TYPE_SYSTEM_ERROR;
			params.dimAmount = 0.0F; // transparent
			params.width = 0;
			params.height = 0;
			params.gravity = Gravity.BOTTOM;
			getWindow().setAttributes(params);
			getWindow().setFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_NOT_TOUCH_MODAL,
					0xffffff);
			setOwnerActivity(activity);
			setCancelable(false);
		}

		public final boolean dispatchTouchEvent(MotionEvent motionevent) {
			return true;
		}

		protected final void onCreate(Bundle bundle) {
			super.onCreate(bundle);
			FrameLayout framelayout = new FrameLayout(getContext());
			framelayout.setBackgroundColor(0);
			setContentView(framelayout);
		}
	}
}
